package pkg

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"me/testMiaosa/common/global"
	"me/testMiaosa/common/model"
	"strconv"
	"sync"
)

// indexExists 查询索引是否存在
func indexExists(index string) (bool, error) {
	request := esapi.IndicesExistsRequest{
		Index: []string{index},
	}

	do, err := request.Do(context.Background(), global.Es)
	if err != nil {
		return false, err
	}
	defer do.Body.Close()

	return do.StatusCode == 200, nil
}

// deleteIndex 删除索引
func deleteIndex(index string) error {
	req := esapi.IndicesDeleteRequest{
		Index: []string{index},
	}
	res, err := req.Do(context.Background(), global.Es)
	if err != nil {
		return fmt.Errorf("删除索引时出错: %w", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return fmt.Errorf("删除索引时出错: %s", res.String())
	}
	return nil
}

// createIndexWithIKAnalyzer 创建ES索引(指定字段加上IK分词)
func createIndexWithIKAnalyzer(indexName string) error {
	// 如果索引存在，先删除
	exists, err := indexExists(indexName)
	if err != nil {
		return err
	}
	if exists {
		err := deleteIndex(indexName)
		if err != nil {
			return err
		}
	}

	// 定义索引映射，使用 IK 分词器
	mapping := `{
        "mappings": {
            "properties": {
                "StoreName": {
                    "type": "text",
                    "analyzer": "ik_max_word"
                }
            }
        }
    }`

	req := esapi.IndicesCreateRequest{
		Index: indexName,
		Body:  bytes.NewReader([]byte(mapping)),
	}

	res, err := req.Do(context.Background(), global.Es)
	if err != nil {
		return fmt.Errorf("创建索引时出错: %s", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return fmt.Errorf("创建索引时出错: %s", res.String())
	}

	return nil
}

// SyncEs 同步到ES
func SyncEs(list []*model.SpikeProducts, indexName string) string {
	err := createIndexWithIKAnalyzer(indexName)
	if err != nil {
		log.Fatalf("Error creating index with IK analyzer: %s", err)
	}

	var wg sync.WaitGroup

	for _, good := range list {
		wg.Add(1)

		go func(good *model.SpikeProducts) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(good)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      indexName,
				DocumentID: strconv.Itoa(int(good.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), global.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()
		}(good)
	}
	wg.Wait()
	return "同步成功"
}
